<?php

namespace App\Admin\Metrics;

use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\ApexCharts\Chart;

class DeviceBar extends Chart
{
    public function __construct($containerSelector = null, $options = [])
    {
        parent::__construct($containerSelector, $options);

        $this->setUpOptions();
    }

    public function ini()
    {

    }

    /**
     * 初始化图表配置
     */
    protected function setUpOptions()
    {
        $color = Admin::color();

        $colors = [$color->primary(), $color->primaryDarker()];

        $this->options([
            'colors' => $colors,
            'chart' => [
                'type' => 'bar',
                'height' => 430
            ],
        ]);
    }

    /**
     * 处理图表数据
     */
    protected function buildData()
    {
        $device = User::query()->select('device')
            ->selectRaw("count(id) as number")
            ->groupBy('device')
            ->get()
            ->each(function ($item) {
                return $item->device = User::DEVICE_MAP[$item->device];
            })->toArray();
        // 执行你的数据查询逻辑
        $data = [
            [
                'data' => array_column($device, 'number')
            ],
        ];
        $categories = array_column($device, 'device');

        $this->withData($data);
        $this->withCategories($categories);
    }

    /**
     * 设置图表数据
     *
     * @param array $data
     *
     * @return $this
     */
    public function withData(array $data)
    {
        return $this->option('series', $data);
    }

    /**
     * 设置图表类别.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withCategories(array $data)
    {
        return $this->option('xaxis.categories', $data);
    }

    /**
     * 渲染图表
     *
     * @return string
     */
    public function render()
    {
        $this->buildData();

        return parent::render();
    }
}
